<template>
  <div class="hl-login">
    <van-field v-model="phone" :disabled="disabled || loading" type="tel" size="large" :maxlength="11" clearable autofocus left-icon="phone-o" style="color: #999" placeholder="请输入登录账户" />
    <van-field v-model="passWord" :disabled="disabled || loading" type="password" size="large" :maxlength="64" clearable left-icon="certificate" style="color: #999" placeholder="请输入登录密码" />
    <div style="margin: 16px">
      <van-button round block :loading="loading" loading-text="正在登陆..." :disabled="disLogin" type="info" @click="onLogin">立即登录</van-button>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { isPhone, isSpace } from '../../utils/validate'
import { getStoreStr, setStore } from '../../utils/storage'
import { Login } from '../../api/store'
import { Field } from 'vant'
const key = 'terminal_phone'
export default {
  name: 'Login',
  components: {
    [Field.name]: Field
  },
  data() {
    return {
      disabled: false,
      loading: false,
      phone: getStoreStr(key),
      passWord: null
    }
  },
  computed: {
    disLogin: function () {
      //登陆是否不可用
      return !(isPhone(this.phone) && !isSpace(this.passWord))
    }
  },
  methods: {
    ...mapActions(['setLogin']),
    //立即登录
    onLogin() {
      const { phone, passWord, setLogin } = this
      if (!isPhone(phone)) {
        this.$toast('手机号码格式错误')
        return false
      }
      if (isSpace(passWord)) {
        this.$toast('请输入密码')
        return false
      }
      this.loading = true
      Login({ phone, passWord })
        .then(res => {
          setLogin(res)
          setStore(key, phone)
          this.$toast.success('登录成功')
          //如果有重定向
          const { redirect } = this.$route.query
          if (redirect) this.$router.replace(redirect)
          else this.$router.replace({ name: 'Home' })
        })
        .catch(err => {
          this.$dialog.alert({ title: '错误信息', message: err })
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>
